package com.example.entitydemo.pojo;


import com.example.entitydemo.base.utils.SpringContextUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.experimental.FieldDefaults;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;

@Slf4j
@Data
@FieldDefaults(makeFinal = true, level = lombok.AccessLevel.PRIVATE)
public class BaseEntity<T,M> {
    Date createTime;
    Date updateTime;
    @JsonIgnore
    M mapper;

    public BaseEntity() {
        this.createTime = new Date();
        this.updateTime = new Date();
        //获取对应实体类的mapper 通过名字获取
        String beanName = this.getClass().getSimpleName();
        //首字母转化为小写
        beanName = beanName.substring(0,1).toLowerCase()+beanName.substring(1);
        this.mapper =  (M) SpringContextUtils.getBean(beanName+"Mapper");
        log.debug("mapper={}", this.mapper);
    }


    public void save(){
        //通过反射调用mapper的save方法
        try {
            this.mapper.getClass().getMethod("save",this.getClass()).invoke(this.mapper,this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void update(){
        //通过反射调用mapper的save方法
        try {
            this.mapper.getClass().getMethod("update",this.getClass()).invoke(this.mapper,this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteById(){
        //通过反射调用mapper的save方法
        try {
            this.mapper.getClass().getMethod("deleteById",this.getClass()).invoke(this.mapper,this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<T> select(){
        //通过反射调用mapper的save方法
        try {
            //下面这句代码有错误 请你解决
           return (List<T>) this.mapper.getClass().getMethod("select",this.getClass()).invoke(this.mapper,this);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
